<template>
	<view>
    <z-nav-bar id="nav" bgColor="#ffffff" :title="pageTitle"></z-nav-bar>
		<view style="padding: 34rpx 32rpx 0;">
			<view class="cell-box">
				<view class="title">
				    地址
				</view>
				<view class="add grey-bg flex-center-between" @tap="chooseAddress">
					<text :style="isAdd?'color:#333;':''">{{addressForm.recipientAddress?addressForm.recipientAddress:'请选择地址'}}</text>
					<image src="http://www.xvopen.com/xiaoV/img1/add.png" mode=""></image>
				</view>
			</view>
			<view class="cell-box">
				<view class="title">
					门牌号
				</view>
				<view class="grey-bg">
					<input type="text" name="region" v-model="addressForm.recipientHouseNumber" placeholder="单元、门牌号，如：4单元301" placeholder-class="place-class" />
				</view>
			</view>
			<view class="cell-box">
				<view class="title">
					联系人
				</view>
				<view class="grey-bg">
					<input type="text" name="userName" v-model="addressForm.recipientName" placeholder="联系人姓名" placeholder-class="place-class" />
				</view>
			</view>
			<view class="cell-box">
				<view class="title">
					电话
				</view>
				<view class="grey-bg">
					<input type="number" name="phone" v-model="addressForm.recipientPhone" placeholder="手机号/座机号" placeholder-class="place-class" maxlength="11"/>
				</view>
			</view>
      <view class="cell-box">
        <view class="title">
          默认地址
        </view>
        <view class="grey-bg">
          <up-switch :activeValue="1" :inactiveValue="0" v-model="addressForm.defaultAddress"></up-switch>
        </view>
      </view>


		</view>
		<main-button :margin="'0 32rpx'" @click="addAddress">保存地址</main-button>
		<main-button :margin="'16rpx 32rpx 0'" :isGradient="false" v-if="addressId" @click="deleteAddress">删除地址</main-button>

		<view v-if="isCommonAdd" class="common-addresses">
			<view class="title">
				常用地址
			</view>
			<view class="add-box flex-center-between" v-for="(item,index) in addressList" :key="index">
				<view class="left" @click="goBackWithParam(item)">
				{{item.userName}} <text>{{item.phone}}</text>
				<view class="add">
					{{item.address}}
					</view>
				</view>
				<view class="right" @click="goBackWithParam(item)">
					<image src="http://www.xvopen.com/xiaoV/img1/add.png" mode=""></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { onLoad } from '@dcloudio/uni-app';
	// import { updateUserAddress,UserAddress,userAddressList,deleteUserAddress } from '@/api/user';
	import { navigateBack, navigateTo } from '@/utils/navigator'
	import {onMounted,ref,reactive,nextTick} from "vue";
  import {addressAdd,addressEdit} from '@/api/pagesMy/address'
import js from '@eslint/js';
//-----------------------------------data--------------------
 //地址list
  const addressForm =reactive({
    recipientName:"",
    recipientPhone:"",
    recipientAddress:"",
    recipientHouseNumber:"",
    latitude:"",
    longitude:"",
    defaultAddress:0

  })
	let	addressList = ref([])
	let pageTitle = ref('')
	let isCommonAdd = ref(false)
	let address = ref('点击搜索地址')
	let isAdd = ref(false)

	//地址ID
	let addressId = ref(null)
	//手机号
	let phone = ref(null)
	//联系人
	let userName = ref(null)
	//门牌
	let region = ref(null)
	const type = ref(null)


  //返回上一页



//------------------------------------onload-----------------

	onLoad((e)=>{
		if(e.type){
			type.value = e.type
		    pageTitle.value = '编辑地址'
		   let addressInfo  = JSON.parse(e.addressInfo) 
		   Object.keys(addressInfo).forEach(key => {
		     if(addressInfo[key]){
		       addressForm[key] = addressInfo[key]
		     }
		   })
			
		}else{
			pageTitle.value = '添加地址'
		}
	})


//-----------------------------------function----------------

	function chooseAddress(){
		uni.chooseLocation({
			success: function (res) {
				console.log('位置名称：' + res.name);
				console.log('详细地址：' + res.address);
				console.log('纬度：' + res.latitude);
				console.log('经度：' + res.longitude);
        addressForm.recipientAddress = res.name
        addressForm.latitude = res.latitude
        addressForm.longitude = res.longitude
        nextTick(()=>{

          isAdd.value = true
        })


			}
		});
	}



	function addAddress(){
		if( !addressForm.recipientAddress ){
			uni.showToast({ title: '请选择地址', icon: 'none' })
			return
		}
		if(!addressForm.recipientHouseNumber){
			uni.showToast({ title: '请填写门牌号', icon: 'none' })
			return
		}
		if(!addressForm.recipientName){
			uni.showToast({ title: '请填写联系人姓名', icon: 'none' })
			return
		}
		if(!addressForm.recipientPhone){
			uni.showToast({ title: '请填写联系电话', icon: 'none' })
			return
		}
    /**写校验手机号是否正确**/
    if(!(/^1[3456789]\d{9}$/.test(addressForm.recipientPhone))){
      uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }
	if(type.value ){
		addressEdit({
		...addressForm
		}).then(res=>{
			uni.showToast({ title: '修改成功', icon: 'none' })
			setTimeout(()=>{uni.navigateBack()},500)
		})

	}else{
	addressAdd({
		...addressForm
		}).then(res=>{
		uni.showToast({ title: '添加成功', icon: 'none' })
		setTimeout(()=>{uni.navigateBack()},500)
		})
	}
   


	}


	function goBackWithParam(item) {
      // 设置要传递的参数到全局变量（或其他方式）
      uni.setStorageSync('userAddres', item);
      // 使用 navigateBack 回到上一页
      uni.navigateBack();
    }

	function deleteAddress(){
		deleteUserAddress({addressId:addressId.value}).then(res=>{
			console.log(res)
			if(res.code==200){
				uni.showToast({title:'删除成功',icon:'none'})
				setTimeout(()=>{uni.navigateBack()},500)
			}
		}).catch(err => {
			uni.showToast({ title: '删除失败', icon: 'none' })
		})
	}

</script>

<style>
	page{
		background-color: #fff;
	}
</style>
<style lang="scss">
	@import "../style/common.scss";
	.cell-box{
		font-size: 32rpx;
		color: #000;
		margin-bottom: 43rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		.title{
			width: 96rpx;
		}
		.grey-bg{
			width: 566rpx;
			height: 80rpx;
			border-radius: 16rpx;
			background-color: #F6F6F6;
			padding: 20rpx 32rpx;
			margin-left: 24rpx;
			font-size: 28rpx;
		}
		.add{
			color:#999;font-size:28rpx;
			image{
				width: 32rpx;
				height: 35rpx;
			}
		}
	}
	.place-class{
		color:#999;font-size:28rpx;
	}
	.common-addresses{
		border-top: 16rpx solid #F6F6F6;
		margin-top: 16rpx;
		padding-bottom: 118rpx;
		.title{
			padding: 32rpx 0 16rpx;
			margin: 0 32rpx;
			font-size: 32rpx;
			font-weight: bold;
		}
	}
</style>
